package com.itheima.web.interceptor;

import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.Admin;
import com.itheima.web.manager.AdminManeger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private AdminManeger adminManeger;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (StrUtil.isEmpty(token)){
            response.setStatus(401);
            return false;
        }
        Admin admin = adminManeger.profile(token);
        if (admin==null){
            response.setStatus(401);
            return false;
        }
        //设定为当前线程
        AdminHolder.setAdmin(admin);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.remove();
    }
}
